import { AppService } from './app.service';
import { Controller, Get, Req, Post, UseGuards, BadRequestException, Body } from '@nestjs/common';
import { LocalAuthGuard } from './common/auth/local-auth.guard';
import { AuthService } from './common/auth/auth.service';
import { SkipJwtAuth, Request } from './common/auth';
// import { Roles } from './common/role/roles.decorator';
import { Roles } from '@zeronejs/role-easy';

import { Role } from './common/role/enums';
import { UserService } from '@api/user/user.service';
import { CreateUserDto } from '@api/user/dto/create-user.dto';
import { encryptedUserPassword } from '@zeronejs/utils';

@Controller()
export class AppController {
    constructor(
        private readonly appService: AppService,
        private authService: AuthService,
        private usersService: UserService
    ) {}

    @Get()
    @Roles(Role.Admin)
    getHello(): string {
        return this.appService.getHello();
    }
    @SkipJwtAuth()
    @UseGuards(LocalAuthGuard)
    @Post('auth/login')
    async login(@Req() req: Request) {
        // return req.user;
        return this.authService.login(req.user);
    }

    @SkipJwtAuth()
    @Post('auth/register')
    async register(@Body() createUserDto: CreateUserDto) {
        const user = await this.usersService.findOneByUsername(createUserDto.username);
        if (user) {
            throw new BadRequestException('用户名已存在');
        }
        let newUser;
        try {
            newUser = await this.usersService.create({
                ...createUserDto,
                password: await encryptedUserPassword(createUserDto.password),
            });
        } catch (e) {
            throw new BadRequestException('注册失败', e?.message);
        }

        // return req.user;
        return this.authService.login(newUser);
    }
    // @UseGuards(JwtAuthGuard)
    @Get('profile')
    getProfile(@Req() req: Request) {
        return req.user;
    }
}
